<template>
  <view>
    <view class="">
      <!-- 头部搜索框 -->
      <uni-search-bar @input="getKeyword" radius="100" cancelButton="none" clearButton="auto" focus="true">
      </uni-search-bar>
      <!-- 搜索列表展示 -->
      <view class="search-list" v-if="searchList.length !== 0">
        <view class="search-item" v-for="(item, i) in searchList" :key="i" @click="goToDetail(item)">
          <!-- 此处需要处理超出部分单行显示， 只能用一行显示的标签 -->
          <view class="search-text">{{item.goods_name}}</view>
          <uni-icons type="arrowright"></uni-icons>
        </view>
      </view>
      <!-- 历史记录 -->
      <view class="history-box" v-else>
        <view class="history-header">
          <text>搜索记录</text>
          <uni-icons type="trash" size="17" @click="deleteHis"></uni-icons>
        </view>
        <view class="history-list">
          <uni-tag :text="item" @click="bindClick(item)" v-for="(item, i) in histories" :key="i"></uni-tag>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null,
        kw: '',
        searchList: [
          // {
        //     "goods_id": 57332,
        //     "goods_name": "400毫升 海鲜食品冷藏冰包 注水冰袋医用冰袋户外冷藏保鲜熟食冷藏反复使用（10个装）"
        //   },
        //   {
        //     "goods_id": 57194,
        //     "goods_name": "亿力洗车工具汽车美容用品海绵刷不伤车漆擦车海棉清洁海绵"
        //   },
        //   {
        //     "goods_id": 57332,
        //     "goods_name": "400毫升 海鲜食品冷藏冰包 注水冰袋医用冰袋户外冷藏保鲜熟食冷藏反复使用（10个装）"
        //   },
        //   {
        //     "goods_id": 57194,
        //     "goods_name": "亿力洗车工具汽车美容用品海绵刷不伤车漆擦车海棉清洁海绵"
        //   },
        //   {
        //     "goods_id": 57332,
        //     "goods_name": "400毫升 海鲜食品冷藏冰包 注水冰袋医用冰袋户外冷藏保鲜熟食冷藏反复使用（10个装）"
        //   },
        //   {
        //     "goods_id": 57194,
        //     "goods_name": "亿力洗车工具汽车美容用品海绵刷不伤车漆擦车海棉清洁海绵"
        //   }
        ],
        // historyList: ['a', 'app', 'apple','a', 'app', 'apple','a', 'app', 'apple','a', 'app', 'apple']
        historyList: []
      };
    },
    computed: {
      histories() {
        // this.historyList.reverse() 这种写法有问题， 修改了原数组
        return [...this.historyList].reverse()
      }
    },
    onLoad() {
      this.getHistoryKw()
    },
    methods: {
      getKeyword(e) {
        // 设置防抖： 只执行最后一次。
        if (this.timer) {
          // 清空定时器需要指定是清空谁
          clearTimeout(this.timer)
          this.timer = null
        }
        // 创建一个计时器
        this.timer = setTimeout(() => {
          this.kw = e
          // 根据kw发起请求
          this.getKwList(e)
        }, 1000)
      },
      // 获取搜索框关键字列表
      async getKwList() {
        // 输入框是否为空
        if (this.kw.length === 0) {
          this.searchList = []
          return
        }
        const {
          data
        } = await uni.$http.get('/api/public/v1/goods/qsearch?query=' + this.kw)
        if (data.meta && data.meta.status !== 200) return uni.$showMessage()
        this.searchList = data.message
        // 将内容放进搜索列表zhong
        this.pushHistory()
      },
      // 跳转商品详情页
      goToDetail(item) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      },
      pushHistory() {
        // this.historyList.push(this.kw)
        // 去重， 并将最新的放到最前面
        const set = new Set(this.historyList)
        set.delete(this.kw)
        set.add(this.kw)
        this.historyList = Array.from(set)
        uni.setStorageSync('history', JSON.stringify(this.historyList))
      },
      getHistoryKw() {
        this.historyList = JSON.parse(uni.getStorageSync('history') || '[]')
        // this.historyList = JSON.parse(uni.getStorageSync('history') || '[]')
      },
      deleteHis() {
        this.historyList = []
        uni.setStorageSync('history', JSON.stringify(this.historyList))
      },
      bindClick(kw) {
        // this.kw = kw
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?query=' + kw
        })
      }
    }
  }
</script>

<style lang="scss">
  .search-list {
    padding: 0 5px;

    .search-item {
      display: flex;
      font-size: 12px;
      padding: 13px 0;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #DCDFE6;

      .search-text {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
  .history-box {
    padding: 0 10px;
    .history-header {
      display: flex;
      justify-content: space-between;
      height: 40px;
      font-size: 13px;
      align-items: center;
    }
    .history-list {
      display: flex;
      flex-wrap: wrap;
      uni-tag {
        margin: 5px 0 0 5px;
      }
    }
  }
</style>
